package com.zwxbc.funplay.servlet;

import com.google.gson.Gson;
import com.zwxbc.funplay.entity.Game;
import com.zwxbc.funplay.service.GameService;
import com.zwxbc.funplay.service.impl.GameServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/game")
public class GameServlet extends HttpServlet {
	GameService gameService = new GameServiceImpl();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");

		String action = request.getParameter("action");

		if ("getAll".equals(action)) {
			// 获取所有游戏数据
			handleGetList(request, response);
		} else if ("getById".equals(action)) {
			// 获取单个游戏数据
			handleGetById(request, response);
		} else if ("getGameListByCategoryId".equals(action)) {
			// 根据分类获取游戏列表
			handleGetGameListByCategoryId(request, response);
		} else if ("buyGame".equals(action)) {
			// 购买游戏
			handleBuyGame(request, response);
		}  else {
			// 未知的操作类型
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			response.getWriter().println("未知的操作");
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String action = request.getParameter("action");

		System.out.println(action);
		if ("add".equals(action)) {
			// 添加游戏
			try {
				handleAdd(request, response);
			} catch (ParseException e) {
				throw new RuntimeException(e);
			}
		} else if ("update".equals(action)) {
			// 更新游戏
			try {
				handleUpdate(request, response);
			} catch (ParseException e) {
				throw new RuntimeException(e);
			}
		} else if ("delete".equals(action)) {
			// 删除游戏
			handleDelete(request, response);
		} else {
			// 未知的操作类型
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			response.getWriter().println("Unknown action");
		}
	}

	// 添加新游戏
	private void handleAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		// 从请求中提取参数
		String gameName = request.getParameter("gameName");
		Double price = Double.valueOf(request.getParameter("price"));
		Long developerId = Long.valueOf(request.getParameter("developerId"));
		Long categoryId = Long.valueOf(request.getParameter("categoryId"));
		Long saleCount = Long.valueOf(request.getParameter("saleCount"));
		Double averageRating = Double.valueOf(request.getParameter("averageRating"));
		String gameImage = request.getParameter("gameImage");
		String gameIntroduction = request.getParameter("gameIntroduction");
		String releaseDate = request.getParameter("releaseDate");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(releaseDate);

		// 创建一个 Game 对象
		Game newGame = new Game();
		newGame.setGameName(gameName);
		newGame.setDeveloperId(developerId);
		newGame.setCategoryId(categoryId);
		newGame.setPrice(price);
		newGame.setSalesCount(saleCount);
		newGame.setAverageRating(averageRating);
		newGame.setGameImage(gameImage);
		newGame.setGameIntroduction(gameIntroduction);
		newGame.setReleaseDate(date);

		// 调用服务方法添加新游戏
		boolean success = gameService.addGame(newGame);

		// 发送响应
		sendJsonResponse(response, "{\"success\":" + success + "}");
	}

	// 更新游戏
	private void handleUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		// 从请求中提取参数
		String gameIdParam = request.getParameter("gameId");
		Long gameId = Long.parseLong(gameIdParam);
		String gameName = request.getParameter("gameName");
		Double price = Double.valueOf(request.getParameter("price"));
		Long developerId = Long.valueOf(request.getParameter("developerId"));
		Long categoryId = Long.valueOf(request.getParameter("categoryId"));
		Long saleCount = Long.valueOf(request.getParameter("saleCount"));
		Double averageRating = Double.valueOf(request.getParameter("averageRating"));
		String gameImage = request.getParameter("gameImage");
		String gameIntroduction = request.getParameter("gameIntroduction");
		String releaseDate = request.getParameter("releaseDate");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(releaseDate);

		Game updatedGame = new Game();
		updatedGame.setGameId(gameId);
		updatedGame.setGameName(gameName);
		updatedGame.setDeveloperId(developerId);
		updatedGame.setCategoryId(categoryId);
		updatedGame.setPrice(price);
		updatedGame.setSalesCount(saleCount);
		updatedGame.setAverageRating(averageRating);
		updatedGame.setGameImage(gameImage);
		updatedGame.setGameIntroduction(gameIntroduction);
		updatedGame.setReleaseDate(date);

		System.out.println(updatedGame);
		// 调用服务方法更新游戏
		boolean success = gameService.updateGame(updatedGame);
		// 发送响应
		sendJsonResponse(response, "{\"success\":" + success + "}");
	}

	// 删除游戏
	private void handleDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从请求中提取参数
		String gameId = request.getParameter("gameId");

		// 调用服务方法删除游戏
		boolean success = gameService.deleteGame(Long.parseLong(gameId));

		// 发送响应
		sendJsonResponse(response, "{\"success\":" + success + "}");
	}
	// 购买游戏
	private void handleBuyGame(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 从请求中提取参数
		String gameId = request.getParameter("gameId");
		String playerId = request.getParameter("playerId");

		gameService.buyGame(Long.parseLong(gameId), Long.parseLong(playerId));

		request.setAttribute("gameId", gameId);
		request.getRequestDispatcher("/view/player/gameInfo.jsp").forward(request, response);
//		sendJsonResponse(response, "{\"success\":" + success + "}");
	}

	// 根据ID查询游戏
	private void handleGetById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从请求中提取参数
		String gameIdParam = request.getParameter("gameId");

		Long gameId = Long.parseLong(gameIdParam);

		// 调用方法根据ID获取游戏
		Game game = gameService.getGameById(gameId);

		// 将 Game 对象转换为 JSON 并发送响应
		String jsonData = new Gson().toJson(game);
		sendJsonResponse(response, jsonData);
	}


	private void handleGetList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Game> gameList = gameService.getGameList();
		// 将 Game 对象转换为 JSON 并发送响应
		String jsonData = new Gson().toJson(gameList);
		sendJsonResponse(response, jsonData);
	}

	private void handleGetGameListByCategoryId(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String gameCategoryIdParam = request.getParameter("categoryId");

		Long gameCategoryId = Long.parseLong(gameCategoryIdParam);

		List<Game> gameList = gameService.getGameListByCategoryId(gameCategoryId);
		// 将 Game 对象转换为 JSON 并发送响应
		String jsonData = new Gson().toJson(gameList);
		sendJsonResponse(response, jsonData);
	}

	private void sendJsonResponse(HttpServletResponse response, String jsonData) throws IOException {
		response.setContentType("application/json");
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(jsonData);
		out.flush();
	}
}